package com.fandou.airobot

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Message
import android.util.Log
import android.view.WindowManager
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import com.baidu.aip.asrwakeup3.core.recog.IStatus
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.fandou.airobot.ui.home.HomeFragment
import com.fandou.airobot.ui.voiceassistant.VoiceAssistantActivity
import com.fandou.airobot.ui.voiceassistant.VoiceAssistantEvent
import com.fandou.airobot.utils.AutoStartUtil
import com.fandou.base.ui.DataBindingConfig
import com.fandou.base.ui.callback.SharedViewModel
import com.fandou.paiti.SmartCameraCropActivity
import com.fandou.speech.wakeup.baidu.WakeUpRecogActivity
import com.google.gson.Gson
import com.jeremyliao.liveeventbus.LiveEventBus
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission


class AiRobotActivity : WakeUpRecogActivity() {

    private var mShareViewModel: SharedViewModel? = null

    override fun initViewModel() {
        mShareViewModel = SharedViewModel()
    }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.ai_robot_home_base_frame_layout, mShareViewModel).addBindingParam(BR.vm, mShareViewModel)
    }

    override fun handleMsg(msg: Message) {
        super.handleMsg(msg)
        //当语音唤醒的时候，说的内容是"在"
        if (msg.what == IStatus.STATUS_WAKEUP_SUCCESS) { // 唤醒词识别成功的回调，见RecogWakeupListener
            VoiceAssistantActivity.start(this, "在")
        }
    }

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) //保持屏幕不变黑
        checkAutoStart()
        observeStartAsr()
        observeStopSpeakAndAsr()
        observeStartPaiti()
    }


    private fun observeStartAsr() {
        LiveEventBus
            .get(VoiceAssistantEvent.KEY_START_ASR, VoiceAssistantEvent::class.java)
            .observe(this, Observer {
                LogUtils.dTag("observeStartAsr", "===:" + Gson().toJson(it))
                speaker.stopTts()
                myRecognizer.stop()

                if (it.content.isNullOrEmpty()){
                    startAsr()
                }else {
                    speaker.startTts(it.content) {
                        if (it.isKeepOnAsr) {
                            startAsr()
                        }

                        if (it.isNeed2Close) {
                            LiveEventBus.get(VoiceAssistantEvent.CLOSE_VOICE_ASSISTANT).post("")
                        }
                    }
                }
            })
    }

    /**
     * 订阅停止
     */
    private fun observeStopSpeakAndAsr() {
        LiveEventBus.get(VoiceAssistantEvent.STOP_SPEAK_AND_ASR, String::class.java)
            .observe(this, Observer {
                speaker?.stopTts()
                myRecognizer.stop()


            })
    }

    /**
     * Observe the paiti intent from voice
     */
    private fun observeStartPaiti() {
        LiveEventBus.get(VoiceAssistantEvent.LAUNCHER_TOPIC_SEARCH_ACTIVITY, String::class.java)
            .observe(this, Observer {
                toTopicSearch()
            })
    }

    override fun onAsrBegin() {
        super.onAsrBegin()
        LiveEventBus.get(VoiceAssistantEvent.KEY_ON_ASR_BEGIN).post("")
    }

    /**
     * 识别到的用户的最终结果
     */
    override fun onAsrResult(res: String?) {
        super.onAsrResult(res)
        LiveEventBus.get(VoiceAssistantEvent.KEY_ON_ASR_RESULT).post(res)
    }


    /**
     * 实时更新麦克风的db值，更新语音收集的图形
     */
    override fun updateVolume(volumePercent: Int, volume: Int) {
        super.updateVolume(volumePercent, volume)
        LiveEventBus.get(VoiceAssistantEvent.KEY_ON_UPDATE_VOLUME).post(volume)
    }

    /**
     * 用户说话结束
     */
    override fun onAsrEnd() {
        super.onAsrEnd()
        LiveEventBus.get(VoiceAssistantEvent.KEY_ON_ASR_END).post("")
    }

    /**
     * 语音识别失败回调
     */
    override fun onAsrError(errorCode: Int, subErrorCode: Int, errorMsg: String?) {
        super.onAsrError(errorCode, subErrorCode, errorMsg)
        LiveEventBus.get(VoiceAssistantEvent.KEY_ON_ASR_ERROR).post(errorMsg)
    }

    /**
     * 在线语义识别结果
     */
    override fun onAsrOnlineNluResult(nluResult: String?) {
        LiveEventBus.get(VoiceAssistantEvent.KEY_ON_ASR_ONLINE_NLU_RESULT).post(nluResult)
    }

    /**
     * 进入拍题
     */
    private fun toTopicSearch() {
        AndPermission.with(this)
            .runtime()
            .permission(Permission.Group.STORAGE, Permission.Group.CAMERA)
            .onGranted { permissions: List<String?>? ->
                // Storage permission are allowed.
                val intent = Intent(this, SmartCameraCropActivity::class.java)
                startActivityForResult(intent, HomeFragment.PHOTO_CODE)
            }
            .onDenied { permissions: List<String?>? ->
                showErrorToast(
                    "请先授予权限"
                )
            }
            .start()
    }

    /**
     * 检查是否已经设置了“自启动”权限
     * e.g 目前尚没有任何手段去精准检查程序是否打开了自启动权限。
     */
    private fun checkAutoStart() {
        if (!SPUtils.getInstance().getBoolean("setAutoStart")) {
            AlertDialog.Builder(this).setTitle("温馨提示！")
                .setMessage("为了您能够正常收到闹钟提醒，请开启app自启动权限")
                .setNegativeButton("我已设置") { _, _ ->
                    SPUtils.getInstance().put("setAutoStart", true)
                }
                .setPositiveButton("去设置") { _, _ ->
                    AutoStartUtil.startAutoStartSetting(this)
                }
                .show()
        }
    }

    companion object {

        @JvmStatic
        fun start(context: Context) {
            val starter = Intent(context, AiRobotActivity::class.java)
            context.startActivity(starter)
        }
    }
}